package com.lubase.metadata.service;

import com.lubase.core.extend.LoadSubTableDataService;
import com.lubase.model.DbEntity;
import com.lubase.orm.QueryOption;
import com.lubase.orm.TableFilter;
import com.lubase.model.DbCollection;
import com.lubase.orm.service.DataAccess;
import com.lubase.orm.util.TableFilterWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class MtLakeApplyLoadSubTableDataService implements LoadSubTableDataService {
    @Override
    public String getId() {
        return "1486602281238401024";
    }

    @Override
    public String getParentTableId() {
        return "1479051780712042496";
    }

    @Override
    public String getDescription() {
        return "获取本次入湖申请涉及到的环境信息";
    }

    @Autowired
    DataAccess dataAccess;

    @Override
    public DbCollection loadChildTableData(String dataId) {
        if (StringUtils.isEmpty(dataId)) {
            return null;
        }
        QueryOption queryOption = new QueryOption("mt_lake_detail");
        queryOption.setFixField("ms_database_id,lake_env");
        queryOption.setTableFilter(new TableFilter("mt_lake_apply_id", dataId));
        DbCollection collection = dataAccess.queryAllData(queryOption);
        if (collection.getData().isEmpty()) {
            return null;
        }
        HashMap<String, String> mapEnv = new HashMap<>();
        for (DbEntity entity : collection.getData()) {
            String databaseId = entity.get("ms_database_id").toString();
            String env = entity.get("lake_env").toString();
            if (mapEnv.containsKey(databaseId)) {
                mapEnv.put(databaseId, mapEnv.get(databaseId) + "," + env);
            } else {
                mapEnv.put(databaseId, env);
            }
        }

        TableFilterWrapper filterWrapper = TableFilterWrapper.or();
        mapEnv.forEach((databaseId, env) -> {
            TableFilterWrapper filterWrapper1 = TableFilterWrapper.and();
            filterWrapper1.eq("ms_database_id", databaseId);
            filterWrapper1.in("env_info", env);
            filterWrapper.addFilter(filterWrapper1.build());
        });

        queryOption = new QueryOption("ms_database_info");
        queryOption.setFixField("ms_database_id,env_info,database_code,host,port,lake_database_code");
        queryOption.setTableFilter(filterWrapper.build());
        queryOption.setSortField("ms_database_id");
        return dataAccess.queryAllData(queryOption);
    }

    @Override
    public String getChildTableCode() {
        return "ms_database_info";
    }
}

